package Cn.edu.zafu.bigdata.x.cxy;

import java.io.*;
import java.net.*;

public class TCPClient {
    private Socket socket;
    private PrintWriter out;
    private BufferedReader in;

    public TCPClient(String hostname, int port) {
        try {
            socket = new Socket(hostname, port);
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        } catch (IOException e) {
            System.err.println("无法连接到服务");
            e.printStackTrace();
            System.exit(1);
        }
    }

    public void start() {
        new Thread(this::readMessages).start();
        new Thread(() -> {
            try {
                BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
                System.out.println("请输入用户名:");
                String nickname = stdIn.readLine();
                out.println(nickname);

                System.out.println("请输入信息（输入为空则关闭程序）");
                String message;
                while ((message = stdIn.readLine()) != null) {
                    out.println(message);
                    if (message.isEmpty()) {
                        break;
                    }
                }
                out.close();
                socket.close();
            } catch (IOException e) {
                System.err.println("Error writing to server.");
                e.printStackTrace();
            }
        }).start();
    }

    private void readMessages() {
        try {
            String serverMessage;
            while ((serverMessage = in.readLine()) != null) {
                System.out.println(serverMessage);
            }
        } catch (IOException e) {
            System.err.println("Error reading from server.");
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        TCPClient client = new TCPClient("127.0.0.1", 5678);
        client.start();
    }
}